<template>
  <div class="flyPrice">
    <ListTab
      v-model="tabStatus"
      :show-header="!showMobilePage"
      :tabs="tabs"
      :max-badge="{ num: 10000, str: '1w', unit:'+'}"
      is-table
      @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="min-fill-page flyPrice-list">
      <div v-if="!showMobilePage" class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          is-show-config
          @handelClick="queryClick"
          @queryEmpty="queryEmpty" />
        <createBtn v-if="hasRouteAuth('crm:flyPrice:create')" @click.native="toCreate"/>
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 300px;">
          <u-table
            v-if="list.items.length"
            :data="list.items"
            :border="true"
            :row-height="rowHeight(54)"
            :height="setTableHeight"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @sort-change="sortMethod">
            <u-table-column :min-width="handleTdWidth()" align="left" label="询价编号">
              <template slot-scope="scope">
                <ToolTip :content="handleSnNumber(scope.row.sn)" is-can-click @handelClick="toDetail(scope.row)" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="询价标题" min-width="130">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.title" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="询价说明" min-width="130">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.description" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.status || scope.row.status===0" :open-delay="800" class="item" placement="top" effect="dark">
                  <div slot="content">{{ scope.row.status | flyPriceStatus }}</div>
                  <div style="display:flex;align-items:center">
                    <div :class="`color-${scope.row.status}`" class="dot"/>
                    <div :style="{color:scope.row.status === 3?'#AEB6C7':'#333333'}">{{ scope.row.status | flyPriceStatus }}</div>
                  </div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="待回复数" min-width="100" prop="waitSubmitNum" sortable="custom">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.waitSubmitNum" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="待审核数" min-width="100" prop="waitApprovalNum" sortable="custom">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.waitApprovalNum" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="服务号通知" width="110">
              <template slot-scope="scope">
                <div v-if="typeof scope.row.enableNotification === 'number'">{{ scope.row.enableNotification ? '开启' : '关闭' }}</div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人" min-width="110">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="所属部门">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.departmentName" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="160" prop="createDate" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createDate,'YYYY/MM/DD HH:mm')" />
              </template>
            </u-table-column>
            <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
              <template slot-scope="scope">
                <div class="operate">
                  <div v-if="!showMobilePage && scope.row.status !== 0" class="button-text br" @click="toDetail(scope.row)">查看</div>
                  <MoreOpeator
                    :list="[
                      {label: '查看', handelClick: () => {toDetail(scope.row)}, auth: showMobilePage && scope.row.status !== 0},
                      {label: '编辑', handelClick: () => {toEdit(scope.row)}, disabled: setEditDisable(scope.row)},
                      {label: '删除', handelClick: () => {toDelete(scope.row)}, disabled: setDelDisable(scope.row)},
                    ]"
                  >
                    <div v-if="!showMobilePage" slot="button" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination>
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"/>
            <createBtn v-if="hasRouteAuth('crm:flyPrice:create')" mobile-table @click.native="toCreate"/>
          </template>
          <template v-else>
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios';// 取消未完成请求
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
// 组件
import ListTab from '@/components/ListTab';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
// fitter
import { flyPriceStatus } from '@/filters/status';
import { paramsRangeFormat } from '@/utils/paramsFormat';
// api
import { tabList, queryPriceList, deleteQueryPrice } from '@/api/flyPrice';
import { getDepartmentAll } from '@/api/config';
import { format } from '@/filters/date';
import { showModal } from '@/utils/message';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';

export default {
  components: {
    ListTab,
    EmptyPlaceholder,
    createBtn
  },
  filters: {
    flyPriceStatus
  },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      tabs: [],
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      sortName: '',
      sortType: '',
      tabStatus: -1,
      page: 1,
      perPage: 20,
      paramsObj: {},
      listLoading: false,
      deptTreeList: [],
      rangeKeyArr: [{
        attr: 'createDate',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time',
        addTime: true
      }],
      statusOption: [
        { value: 0, label: '草稿中' },
        { value: 1, label: '询价中' },
        { value: 2, label: '已完成' },
        { value: 3, label: '已作废' }
      ],
      cancelToken: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    tableOutsideHeight() {
      return this.showMobilePage ? 195 : 188;
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'sn', name: '询价编号', labelWidth: '100px', type: 'input' },
        { keyword: 'title', name: '询价标题', labelWidth: '100px', type: 'input' },
        { keyword: 'description', name: '询价说明', labelWidth: '100px', type: 'input' },
        { keyword: 'account', name: '账号', labelWidth: '100px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '100px', type: 'input' },
        // 下拉
        { keyword: 'departmentIds', name: '所属部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'status', name: '状态', type: 'select', options: this.statusOption },
        { keyword: 'enableNotification', name: '服务号通知', type: 'select', options: [{ value: 0, label: '关闭' },
          { value: 1, label: '开启' }] },
        // 日期
        { keyword: 'createDate', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    }
  },
  created() {
    if (this.$route.query && this.$route.query.tabStatus) {
      this.tabStatus = Number(this.$route.query.tabStatus);
    }
    this.queryDeptTreeList();
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'flyPriceCreate' || from.name === 'flyPriceEdit') {
      to.meta.isRedirectCreate = true;
    } else {
      to.meta.isRedirectCreate = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isRedirectCreate) {
      this.fetchData();
    } else {
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        this.fetchData(true);
      }
    }
  },
  methods: {
    hasRouteAuth,
    format,
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData();
    },
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    setDelDisable(row) {
      const statusArr = [0, 3];// 草稿、已作废
      return !((statusArr.includes(row.status) && Number(row.creatorId === this.userInfo.id)) || (statusArr.includes(row.status) && hasRouteAuth('crm:flyPrice:delete')));
    },
    setEditDisable(row) {
      const statusArr = [0];// 草稿且为创建人
      return !(statusArr.includes(row.status) && row.creatorId === this.userInfo.id);
    },
    toEdit(row) {
      const query = {
        id: row.id
      };
      if (row.status === 0) {
        query.isDraft = true;
      }
      this.$router.push({
        name: 'flyPriceEdit',
        query
      });
    },
    getTabs() {
      const params = this.formatParams();
      tabList(params).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.tabs = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.fetchData(true);
    },
    fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      this.getTabs();
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      params.page = this.page;
      params.perPage = this.perPage;
      params.tabStatus = this.tabStatus;
      queryPriceList(params, source.token).then(res => {
        this.listLoading = false;
        this.list.isInit = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
      }).catch(err => {
        this.listLoading = false;
        this.list.isInit = false;
        console.log(err);
      });
    },
    formatParams() {
      const paramsObj = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, paramsObj);
      Object.keys(paramsObj).forEach(key => {
        if (paramsObj[key] && Array.isArray(paramsObj[key])) {
          paramsObj[key] = paramsObj[key].join(',');
        }
      });
      return paramsObj;
    },
    toCreate() {
      this.$router.push({
        name: 'flyPriceCreate'
      });
    },
    toDetail(row) {
      this.$router.push({
        name: 'flyPriceDetail',
        query: {
          id: row.id
        }
      });
    },
    toDelete(row) {
      showModal('确定删除该询价?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        deleteQueryPrice(row.id).then(res => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.fetchData();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    }
  }
};
</script>
<style lang="scss" scoped>
$bgc: #FFBC3D 0, #FD8546 1, #31CC9C 2, #999 3;
	.flyPrice{
		.flyPrice-list{
			margin: 16px 16px 0 16px;
			background-color: #fff;
			padding: 20px 24px 55px 24px;
		}
    .operate{
      display: flex;
      align-items: center;
    }
    .button-text {
      font-weight: 600;
    }
    .border-left {
      position: relative;
      padding-left:6px;
      margin-left: 6px;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -7px;
        width: 1px;
        background: #ddd;
        height: 14px;
      }
    }
		.filter {
			display: flex;
			align-items: center;
      margin-bottom: 16px;
			.create-btn{
				height: 32px;
				font-size: 14px;
				padding: 0 15px;
			}
		}
    .dot {
      width: 4px;
      height: 4px;
      border-radius: 50%;
      margin-right: 5px;
      @each $bgc, $i in $bgc {
        &.color-#{$i} {
          background: $bgc;
        }
      }
    }
    .pointer{
      cursor: pointer;
    }
    .tag-wrap{
      display: flex;
      align-items: center;
    }
    .tag{
      display: inline-block;
      max-width: 60px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color:#406EFF;
      font-size: 12px;
      padding: 0px 8px;
      background: #eff4ff;
      border-radius: 10px;
      margin-right: 4px;
    }
	}
</style>
